package com.dmgis.hndz.controller;

import com.alibaba.fastjson.JSONObject;
import com.dmgis.entity.ContourSetting;
import com.dmgis.hndz.common.result.HttpStatusEnum;
import com.dmgis.hndz.common.result.ResponseResult;
import com.dmgis.hndz.common.utils.SysResult;
import com.dmgis.hndz.common.utils.TxtFileManager;
import com.dmgis.hndz.mapper.Qxaa01aMapper;
import com.dmgis.hndz.mapper.RiskManagementMapper;
import com.dmgis.hndz.pojo.MsgDto;
import com.dmgis.hndz.pojo.Qxaa01a;
import com.dmgis.hndz.pojoVo.LatestMonitoring;
import com.dmgis.hndz.service.DynamicWarningService;
import com.dmgis.hndz.service.RiskManagementService;
import com.dmgis.hndz.service.Ybba01bService;
import com.dmgis.hndz.service.Ybba02bService;
import com.dmgis.service.DmServiceConnector;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class RegionalAutomaticStationController {

    @Autowired
    private Qxaa01aMapper qxaa01aMapper;

    @Autowired
    private RiskManagementMapper riskManagementMapper;

    @Value("${dmgis.serveName}")
    private String serveName;

    @Value("${server.port}")
    private String txtPort;

    @Value("${dmgis.ip}")
    private String dmgisIp;

    @Value("${dmgis.port}")
    private String dmgisPort;

    private static final String pluginClassFullName = "service";

    private static final String methodName = "contour";

    @Value("${dmgis.rect}")
    private String rect;

    @Value("${dmgis.image_url}")
    private String imageUrl;

    @Value("${filePath.txtFilePath}")
    private String txtFile;

    @Autowired
    private TxtFileManager txtFileManager;

    @Autowired
    private Ybba01bService ybba01bService;

    @Autowired
    private Ybba02bService ybba02bService;

    @Autowired
    private RiskManagementService riskManagementService;

    @Autowired
    private DynamicWarningService dynamicWarningService;


    @ApiOperation("累计雨量")
    @GetMapping("/getCumulativeRainfall")
    public SysResult getCumulativeRainfall(String startTime, String endTime) {
        List<Qxaa01a> msgMediumSmallScaleList = qxaa01aMapper.selectList6(startTime, endTime);
        return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }


    @ApiOperation("等值图")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "satrTime", value = "开始时间", dataType = "String", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String", required = true),
            @ApiImplicitParam(name = "elementType", value = "类型，参考：12小时雨量\n" +
                    "24小时雨量\n" +

                    "6小时雨量\n" +

                    "1小时雨量\n" +

                    "3小时雨量\n"

                    , dataType = "String", required = true)
    })
    @PostMapping("/coutView")
    public SysResult coutView(String satrTime, String elementType, String endTime) throws IOException, ParseException {
        String type = "实况";//预报
        //String satrTime ="2023-11-15 10:00:00";
        //String endTime="2023-11-23 16:00:00";
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date satrdate = dateFormat2.parse(satrTime);
        Date enddate = dateFormat2.parse(endTime);
        List<MsgDto> msgMediumSmallScaleList = new ArrayList<>();
        switch (type) {

            case "实况":
//                QueryWrapper<Qxaa01a> Wrapper = new QueryWrapper<>();
//                Wrapper.between("qxaa01a050",satrdate,enddate).eq("qxaa01a030","怀化市");
                List<Qxaa01a> qxaa01aList = qxaa01aMapper.selectList6(satrTime, endTime);
                for (Qxaa01a qxaa01a : qxaa01aList) {
                    msgMediumSmallScaleList.add(new MsgDto(qxaa01a.getQxaa01a070(), qxaa01a.getQxaa01a080(), qxaa01a.getQxaa01a100()));
                }
                break;
            case "预报":
                break;
        }
//        List<MsgDto> msgMediumSmallScaleList = JSON.parseArray(msgListstr, MsgDto.class);
        List<ContourSetting> contourSettingList = riskManagementMapper.queryByElementType(elementType);
        StringBuilder txt = new StringBuilder();
        // 添加基本参数
        txt.append("[基本参数]\n");
        //点的个数
        txt.append(msgMediumSmallScaleList.size()).append(",");
        //分级数
        txt.append(contourSettingList.size()).append(",");
        //服务名
        txt.append(serveName + ",1,1.5,5,1,0,0,1\n");
        // 添加数据
        txt.append("[数据]\n");
        msgMediumSmallScaleList.forEach(longitudeLatitudeValue -> {
            txt.append(longitudeLatitudeValue.getLongitude()).append("\t")
                    .append(longitudeLatitudeValue.getLatitude()).append("\t")
                    .append(longitudeLatitudeValue.getValue()).append("\n");
        });
        // 添加分级参数
        txt.append("[分级参数]\n");
        contourSettingList.forEach(contourSetting -> {
            txt.append(contourSetting.getElementValue()).append(",")
                    .append(contourSetting.getElementColor()).append(",")
                    .append(contourSetting.getElementColor()).append(",")
                    .append("1,0,")
                    .append(contourSetting.getElementColor()).append(",")
                    .append("0,0,0,0").append("\n");
        });
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        // 生成文件名，格式为时间+RefinedForecastingController
        String txtName = dateFormat.format(new Date()) + "-" + "1hourain";

        String txtPath = txtFileManager.writeDataToTxtFile(txt.toString(), txtName);
        //文件夹目录
        String homePath = TxtFileManager.extractFolderPath(txtPath);
        // 一小时删除任务
        TxtFileManager.cleanupTempFiles(homePath, 3600000);

        System.err.println("文件存储路径：" + txtPath);
        String url = "http://" + dmgisIp + ":" + txtPort + "/common/files/" + txtName + ".txt";
        System.err.println(url);

        DmServiceConnector conn = new DmServiceConnector(dmgisIp, dmgisPort);
        String uniqueno = conn.getCallPlugin(pluginClassFullName, methodName, "GetInterpolationWork|" + url);
        System.err.println(uniqueno);
        String imgname = conn.getCallPlugin(pluginClassFullName, methodName, "GetContourPic|" + uniqueno + "|" + serveName + "|500|500|" + rect + "|1");
        Map<String, String> rlt = new HashMap<>();
        rlt.put("imgurl", imgname);
        rlt.put("rect", rect);
        return SysResult.success(rlt);
    }

    @ApiOperation("预警查询")
    @PostMapping("/getYj")
    public SysResult getYj(String startTime, String endTime, Integer yjType, Integer yjLevel) {
        System.out.println("-------------------------------------");
        System.out.println("startTime:" + startTime);
        System.out.println("endTime:" + endTime);
        System.out.println("yjType:" + yjType);
        return SysResult.success(ybba01bService.getYj(startTime, endTime, yjLevel, ""));
    }

    @ApiOperation("预警预报查询")
    @PostMapping("/getProduct")
    public SysResult getProduct(String startTime, String endTime) {
        return SysResult.success(ybba02bService.getProduct(startTime, endTime));
    }

    @ApiOperation(value = "灾点查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "zhaa11a012", value = "统一编号", required = true, defaultValue = "431200", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "zhaa11a020", value = "野外编号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "zhaa11a024", value = "灾害类型01:滑坡 02:崩塌 03:泥石流 04:地面塌陷 06:地裂缝 07:地面沉降 00:不稳定斜坡",
                    required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "zhaa11a022", value = "灾害名称关键字", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "zhaa11a074", value = "威胁财产", required = true, defaultValue = "2023", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "zhaa11a074s", value = "至威胁财产", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "zhaa11a072", value = "威胁人口", required = true, defaultValue = "2023", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "zhaa11a072s", value = "至威胁人口", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "zhaa11a080", value = "规模等级", required = true, defaultValue = "2023", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "zhaa11a084", value = "险情等级", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "zhaa11a082", value = "灾情等级", required = false, dataType = "String", paramType = "query"),
    })
    @PostMapping("getHiddenDangerPoint")
    @ResponseBody
    public ResponseResult getHiddenDangerPoint(@RequestBody JSONObject jsonObject) {
//        return ResponseResult.success(riskManagementService.getHiddenDangerPoint(jsonObject));
        return ResponseResult.success(riskManagementService.getHiddenDangerPointInfo2(jsonObject));
    }


    @ApiOperation(value = "监控信息")
    @PostMapping("/queryLatestMonitoringInfo")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "时间", required = false, defaultValue = "2023-06-30 09:09", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "截至时间", required = false, defaultValue = "2023-07-30 09:09", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "county", value = "县", required = false, defaultValue = "沅陵县", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "waringLevel", value = "预警等级", required = false, defaultValue = "", dataType = "String", paramType = "query")
    })
    public ResponseResult queryLatestMonitoringInfo(@RequestBody JSONObject jsonObject) {
        List<LatestMonitoring> statement = dynamicWarningService.queryLatestMonitoringInfo(jsonObject);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", statement);
    }


}
